import { Draw } from "../../../Draw/Draw";
import { IKonva } from "../../../Interface/IKonva";

/**
 * 表格双击修改配置属性
 */
export function groupTableDbclick(e: IKonva.Event, draw: Draw) {
  e.cancelBubble = true;
  const table = e.target;

  //  1. 拿到数据源
  const { data } = table.attrs;

  //   2. 打开弹窗
  const dialog = draw.getDialog();
  dialog.open({
    title: "表格属性",
    content: createTableHtml(data),
    onConfirm: ({ data }) => {
      table.setAttrs({ data });
      draw.render();
    },
  });
}

/** 根据 data 动态生成 html 内容 */
function createTableHtml(data: string[][]) {
  //   多少列
  const colsNumber = data[0].length;
  //   多少行 - 少一行表头
  const rowsNumber = data.length - 1;

  let template = `
 <div class="konva-root-dialog-table">
    <div class="header">
        <span>行:</span>
        <input type="number" min="1" value="${rowsNumber}" id="konva-root-table-rows" />
        <span>列:</span>
        <input type="number" min="1" value="${colsNumber}" id="konva-root-table-cols" />
    </div>`;

  // 处理表头 - 循环表头处理 data[0]
  let thead = "";
  for (let i = 0; i < colsNumber; i++) {
    thead += `<th><input value="${data[0][i]}" /></th>`;
  }

  // 处理 tbody - 循环表头处理 data[1] - data[rowsNumber]
  let tbody = "";
  for (let i = 1; i < data.length; i++) {
    let tdList = "";
    // 循环每一项 td
    for (let j = 0; j < data[i].length; j++) {
      tdList += `<td><input value="${data[i][j]}" /></td>`;
    }
    tbody += `<tr>${tdList}</tr>`;
  }

  template += `<table> <thead> <tr>${thead}</tr> </thead> <tbody>${tbody}</tbody> </table></div>`;

  return template;
}
